<template>
  <div>
    <el-row gutter="40" type="flex" justify="space-between" style="width: 100%; align-items: flex-start">
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>我的工作台</span>
            <el-button style="float: right; padding: 3px 0" type="text" size="mini">查看更多</el-button>
          </div>
          <el-tabs v-model="activeTab" @tab-click="handleClick">
            <el-tab-pane label="任务" name="task">
              <!-- ECharts 图表的容器 -->
              <div ref="echartsContainer" style="width: 100%; height: 400px;"></div>
            </el-tab-pane>
            <el-tab-pane label="搅拌工具" name="fswTool">
              <div ref="echartsContainer1" style="width: 100%; height: 500px;"></div>
            </el-tab-pane>
            <el-tab-pane label="其他数据" name="other">
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
      <el-col :span="8">
        <Calendar style="width: 100%"></Calendar>
        <!--                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <span>通知公告</span>
                    <el-button style="float: right; padding: 3px 0" type="text">查看更多</el-button>
                  </div>
                  <p>通知1</p>
                  <p>通知2</p>
                </el-card>-->
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 导入 ECharts 核心模块
import * as echarts from 'echarts';
import Calendar from "@/components/Calendar";

export default {
  name: 'DefaultData',
  components: {Calendar},
  data() {
    return {
      activeTab: 'task',
      value: new Date(),
      taskData: [],
      toolData: [],
      mainChartInstance: null, // 存储主图表实例
      mixChartInstance: null, // 存储混合图表实例
    }
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
      this.$nextTick(() => {
        if (tab.name === 'task' && this.mainChartInstance) {
          this.mainChartInstance.resize();
        } else if (tab.name === 'fswTool' && this.mixChartInstance) {
          this.mixChartInstance.resize();
        }
      });
    },
    initMainChart() {
      const ongoingData = this.taskData.map(item => item.ongoing);
      const delayedData = this.taskData.map(item => item.delay);
      const completedData = this.taskData.map(item => item.completed);
      const names = this.taskData.map(item => item.name);
      this.mainChartInstance = echarts.init(this.$refs.echartsContainer);
      this.mainChartInstance.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '2%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          min: 0,
          interval: 1,
          axisLabel: {
            formatter: function (value) {
              return Math.floor(value); // 向下取整，只显示整数部分
            }
          },
        },
        yAxis: {
          type: 'category',
          data: names
        },
        series: [
          {
            name: '进行中',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: '#79BBFF'
            },
            data: ongoingData
          },
          {
            name: '已延期',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: '#ff7f50'
            },
            data: delayedData
          },
          {
            name: '已完成',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: '#90ee90'
            },
            data: completedData
          }
        ]
      });
    },
    initMixChart() {
      this.$nextTick(() => {
        // 提取月份和数据
        const months = [...new Set(this.toolData.map(item => item.requestDeliveryTime.slice(0, 7)))].sort();
        const seriesData = this.toolData.reduce((acc, item) => {
          const month = item.requestDeliveryTime.slice(0, 7);
          if (!acc[item.name]) {
            acc[item.name] = Array(months.length).fill(0);
          }
          const index = months.indexOf(month);
          acc[item.name][index] += item.number;
          return acc;
        }, {});

        // 转换数据格式以适应图表
        const processedData = Object.keys(seriesData).map(key => ({
          name: key,
          type: 'line',
          data: seriesData[key],
          smooth: true,
          seriesLayoutBy: 'row',
          emphasis: {focus: 'series'}
        }));

        // 饼图数据
        const pieData = processedData.map(line => ({
          name: line.name,
          value: line.data.reduce((a, b) => a + b, 0)
        }));

        // 图表配置
        const option = {
          legend: {},
          tooltip: {
            trigger: 'axis',
            showContent: false
          },
          xAxis: {
            type: 'category',
            data: months
          },
          yAxis: {
            type: 'value'
          },
          grid: {top: '55%'},
          series: [
            ...processedData,
            {
              type: 'pie',
              id: 'pie',
              radius: '30%',
              center: ['50%', '25%'],
              data: pieData,
              emphasis: {focus: 'self'},
              label: {
                formatter: '{b}: {c} ({d}%)'
              }
            }
          ]
        };

        // 初始化图表实例并设置配置
        this.mixChartInstance = echarts.init(this.$refs.echartsContainer1);
        this.mixChartInstance.setOption(option);

        // 更新饼图数据
        this.mixChartInstance.on('updateAxisPointer', (event) => {
          const xAxisInfo = event.axesInfo[0];
          if (xAxisInfo) {
            const dimension = xAxisInfo.value + 1;
            this.mixChartInstance.setOption({
              series: {
                id: 'pie',
                label: {
                  formatter: `{b}: {@[${dimension}]} ({d}%)`
                },
                encode: {
                  value: dimension,
                  tooltip: dimension
                }
              }
            });
          }
        });
      });
    }
  },
  mounted() {
    this.$store.dispatch('fetchTodoCount');
    this.$store.dispatch('fetchReminderCount')// 获取待办任务数量
    this.$http.get("/task/status").then((response) => {
      if (response.data.code == 1) {
        this.taskData = response.data.data;
        /*console.log(JSON.stringify(this.taskData, null, 2))*/
        this.initMainChart();
      }
    });
    this.$http.get("/tool/orderItem").then((response) => {
      if (response.data.code == 1) {
        this.toolData = response.data.data;
        /*
                console.log(JSON.stringify(this.toolData, null, 2))
        */
        this.initMixChart();
      }
    });
  }
}
</script>

<style scoped>
::v-deep .el-calendar .el-calendar-day {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center;
}

::v-deep .el-calendar {
  width: 100%; /* 根据需要调整这个值 */
}

.is-selected {
  color: #1989FA;
}
</style>